﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;

namespace AndreySmirnov.BLToolkitUtils.VSPackage.UI
{
	public class EnumToBoolConverter<T> : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (!(parameter is string) || string.IsNullOrEmpty((string)parameter))
				return DependencyProperty.UnsetValue;
			if (Enum.IsDefined(value.GetType(), value) == false)
                return DependencyProperty.UnsetValue;

			var param = Enum.Parse(typeof (T), (string) parameter);
			if (value is T && (targetType == typeof(bool) || targetType == typeof(bool?)))
			{
				return param.Equals(value);
			}
			return DependencyProperty.UnsetValue;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (!(value is bool || value is bool?) || string.IsNullOrEmpty((string)parameter))
				return DependencyProperty.UnsetValue;
			if ((bool)value)
			{
				return Enum.Parse(typeof(T), (string)parameter);
			}
			return DependencyProperty.UnsetValue;
		}
	}
}
